<template>
    <div class="tr basic-ist">
        <!-- 基础数据-->
        <div class="tr-top">
            <div class="left">
                <div class="itm"><el-button :disabled="!permissionData.data['filelist-post']"
                        @click="addEv">新增</el-button></div>
            </div>
            <div class="right">
                <div class="itm">
                    <el-input v-model="tableObjData.name__like" style="width: 240px;" clearable placeholder="名称搜索" />
                </div>
                <div class="itm"><el-button :disabled="!permissionData.data['filelist-get']"
                        @click="getEv(true)">查询</el-button></div>
            </div>
        </div>
        <div class="table-content">
            <el-table @row-dblclick="rowDblclickEv" empty-text="暂无数据" border height="100%" :data="tableListData">
                <el-table-column align="center" show-overflow-tooltip header-align="center" prop="id" label="文件ID"
                    width="250" />
                <el-table-column align="center" show-overflow-tooltip header-align="center" prop="name" label="文件名称"
                    width="180" />
                <el-table-column align="center" show-overflow-tooltip header-align="center" prop="url" label="文件地址"
                    width="260" />
                <el-table-column align="center" show-overflow-tooltip header-align="center" prop="rem" label="备注"
                    width="180" />

                <el-table-column show-overflow-tooltip align="center" header-align="center" label="操作" width="200">
                    <template #default="scope">
                        <el-button link type="primary" :disabled="!permissionData.data['filelist-get']" size="small"
                            @click="uploatFiledGetEv(scope.row)">
                            预览
                        </el-button>
                        <el-button link type="primary" :disabled="!permissionData.data['filelist-get']" size="small"
                            @click="updateSelRowEv(scope.row)">
                            修改
                        </el-button>
                        <el-popconfirm placement="left-end" width="220" confirm-button-text="删除" cancel-button-text="取消"
                            icon-color="#626AEF" confirm-button-type="text" title="是否确认永久是删除此数据"
                            @confirm="deleteSelRowEv(scope.row)">
                            <template #reference>
                                <el-button link type="primary" :disabled="!permissionData.data['filelist-get']"
                                    size="small">删除</el-button>
                            </template>
                        </el-popconfirm>

                    </template>
                </el-table-column>
            </el-table>
        </div>
        <pagination v-show="tableObjData.total > 0" :total="tableObjData.total" v-model:page="tableObjData.page"
            v-model:limit="tableObjData.pageSize" @pagination="getEv(true)" />

        <el-dialog :close-on-click-modal="false" draggable v-model="dialogVisible" :title="isAdd == true ? '新增' : '修改'"
            width="400" :before-close="handleClose">
            <template #header>
                {{ isAdd == true ? '新增' : '修改' }} <span style="font-size: 12px; color: red;"></span>
            </template>
            <el-form>
                <el-row>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label-width="100" label="文件名称">
                            <el-input v-model="ruleForm.name" style="width: 100%" placeholder="文件名称" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label-width="100" label="文件名称">
                            <el-upload ref="refupload" class="upload-demo" :auto-upload="true" :limit="1"
                                :before-upload="beforeAvatarUpload" :on-exceed="handleExceed">
                                <template #trigger>
                                    <!-- <el-button type="primary">选择文件</el-button> -->
                                    <el-icon class="avatar-uploader-icon">
                                        <Plus />
                                    </el-icon>
                                </template>
                                <template #tip>
                                    <div class="el-upload__tip text-red">
                                        每次只能上传一个文件
                                        仅支持['jpeg', 'jpg', 'png',]
                                    </div>
                                    <div v-if="uploadName != ''">
                                        {{ uploadName }}/{{ ruleForm.size }}kb
                                    </div>
                                </template>
                            </el-upload>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label-width="100" label="文件备注">
                            <el-input v-model="ruleForm.rem" style="width: 100%" placeholder="备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogSuerEv()">确认</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 图片预览 -->
        <el-dialog v-model="dialogVisibleImage" title="Tips" width="30%" :before-close="handleClose">
            <span><img :src="src" v-if="src != ''" /></span>

        </el-dialog>
    </div>
</template>

<script setup>

import { ref, reactive, onMounted, onActivated } from 'vue'
import { ListGet, ListPost, PkGet, PkPut, PkDelete, uploatFiledPost, uploatFiledGet } from '@/api/setting/file/index.js'
import { permissionStore } from '@/stores/index.js'
import { loadingStore } from '@/stores/index.js'
import { Plus } from '@element-plus/icons-vue'
const loading = loadingStore()
// 权限数据
const permissionData = permissionStore()
const emit = defineEmits(['dbRowBasicFile'])
let tableObjData = reactive({
    name__like: null,
    page: 1,
    total: 0,
    has_next: false,
    has_prev: false,
    pages: 0,
    pageSize: 20
})
const ruleForm = reactive({
    name: '',
    size: 0,
    postfix: '',
    url: '',
    rem: ''

})
let tableListData = ref([])
let isAdd = ref(true)
let dialogVisible = ref(false)
let dialogVisibleImage = ref(false)
let refupload = ref(null)
let uploadName = ref('')
let rowId = ref('')

let src = ref('')

onMounted(() => {
    getEv()
})

onActivated(() => {

})
// 文件上传处理
const beforeAvatarUpload = async (file) => {
    uploadName.value = file.name
    ruleForm.size = parseFloat((file.size / 1024).toFixed(2))
    const formData = new FormData();
    formData.append('uploadFiled', file);
    loading.loading = true
    try {
        let arr_data = await uploatFiledPost(formData)
        if (arr_data.status != 200) {
            return
        }
        console.log(arr_data.data.result)
        ruleForm.url = arr_data.data.result.url
        ruleForm.postfix = arr_data.data.result.postfix
    } catch (error) {

    } finally {
        loading.loading = false
    }
    return false
}
const handleExceed = (files) => {
    refupload.value.clearFiles()
    const file = files[0]
    file.uid = genFileId()
    refupload.value.handleStart(file)
}

// 查询数据
const getEv = async (msg) => {
    loading.loading = true
    try {
        let arr_data = await ListGet(tableObjData)
        if (arr_data.status != 200) {
            return
        }
        if (msg == true) {
            ElMessage.success('查询成功')
        }
        tableListData.value = arr_data.data.result.data
        tableObjData.total = arr_data.data.result.total
        tableObjData.has_next = arr_data.data.result.has_next
        tableObjData.has_prev = arr_data.data.result.has_prev
        tableObjData.pages = arr_data.data.result.pages
        tableObjData.pageSize = arr_data.data.result.pageSize

    } catch (error) {
        ElMessage.error('查询接口请求失败' + error)
    } finally {
        loading.loading = false
    }
}
const addEv = () => {
    dialogVisible.value = true
    isAdd.value = true
    ruleForm.name = ''
    ruleForm.postfix = ''
    ruleForm.url = ''
    ruleForm.rem = ''
    ruleForm.size = 0
}
// 重置dialogVisible
const resetDialogVisible = () => {
    dialogVisible.value = false
    isAdd.value = true
    ruleForm.name = ''
    ruleForm.postfix = ''
    ruleForm.url = ''
    ruleForm.rem = ''
    ruleForm.size = 0
}
// 关闭出发事件
const handleClose = (done) => {
    isAdd.value = true
    done()
}
// 弹窗确认事件
const dialogSuerEv = async () => {
    if (isAdd.value == true) {
        console.log('新增数据')
        await addDataEv()
    } else {
        console.log('修改数据')
        await updateRowEv()
    }

}
// 新增数据
const addDataEv = async () => {
    if (ruleForm.name == '') {
        ElMessage.error('名称不能为空')
        return
    }
    if (ruleForm.url == '') {
        ElMessage.error('请文件上传文件')
        return
    }
    loading.loading = true
    try {


        let arr_data = await ListPost(ruleForm)
        if (arr_data.status != 200) {
            return
        }
        await getEv(false)
        resetDialogVisible()
        ElMessage.success('新增成功')
    } catch (error) {
        ElMessage.error('新增接口请求失败' + error)
    } finally {
        loading.loading = false
    }
}

// 预览文件
const uploatFiledGetEv = async (row) => {
    loading.loading = true
    src.value = ''
    try {
        let arr_data = await uploatFiledGet({ id: row.id })
        if (arr_data.status != 200) {
            return
        }
        console.log(arr_data)
        const base64String = btoa(
            new Uint8Array(arr_data.data).reduce((data, byte) => data + String.fromCharCode(byte), '')
        );
        src.value = `data:image/${row.postfix};base64,` + base64String
        dialogVisibleImage.value = true
    } catch (error) {
        ElMessage.error('获取文件接口请求失败' + error)
    } finally {
        loading.loading = false
    }

}

// 点击修改获取单个数据
const updateSelRowEv = async (row) => {
    loading.loading = true
    try {
        let arr_data = await PkGet(row.id)
        if (arr_data.status != 200) {
            return
        }
        isAdd.value = false
        dialogVisible.value = true
        rowId.value = row.id
        ruleForm.name = arr_data.data.result.name
        ruleForm.url = arr_data.data.result.url
        ruleForm.size = arr_data.data.result.size
        ruleForm.rem = arr_data.data.result.rem
        uploadName.value = arr_data.data.result.url

    } catch (error) {
        ElMessage.error('获取单个数据接口请求失败' + error)
    } finally {
        loading.loading = false
    }
}

// 修改数据
const updateRowEv = async () => {

    loading.loading = true
    try {
        let arr_data = await PkPut(ruleForm, rowId.value)
        if (arr_data.status != 200) {
            return
        }

        tableObjData.name__like = arr_data.data.result.name
        await getEv(false)
        resetDialogVisible()
        ElMessage.success('修改成功')
    } catch (error) {
        ElMessage.error('修改接口请求失败' + error)
    } finally {
        loading.loading = false
    }
}

// 删除数据
const deleteSelRowEv = async (row) => {
    loading.loading = true
    try {
        let arr_data = await PkDelete(row.id)
        if (arr_data.status != 200) {
            return
        }
        await getEv(false)
        ElMessage.success('删除成功')
    } catch (error) {
        ElMessage.error('删除接口请求失败' + error)
    } finally {
        loading.loading = false
    }
}

// 双击行
const rowDblclickEv = (row) => {
    console.log("双击行")
    console.log(row)
    emit("dbRowBasicFile", row)
}

</script>

<style lang='less' scoped>
@tr-top-height: 50px;

// .tr {
//     height: 900px;
// }
.basic-ist {
    height: 100%;
}

.tr-top {
    height: @tr-top-height;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .right {
        display: flex;
        align-items: center;
    }

    .itm {
        padding-right: 4px;
        box-sizing: border-box;
    }
}

.table-content {
    height: calc(100% - var(--tr-top-height) - var(--tr-page-height));
}

.dialog-content {
    display: flex;
    align-items: center;
    height: 40px;

    .left {
        width: 60px;
        text-align: right;
        padding-right: 5px;
        box-sizing: border-box;
    }
}

/* 自定义表格悬停颜色类 */
:deep(.el-table__cell:hover) {
    cursor: pointer
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
    box-sizing: border-box;
    border: 1px dashed #dcdfe6
}

.el-icon.avatar-uploader-icon:hover {
    box-sizing: border-box;
    border: 1px dashed #409eff
}
</style>